#include <iostream>
#include <cstdio>
#include <stdlib.h>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
using namespace std;
//./udpclient server_ip server_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        printf("Usage: ./udpclient server_ip server_port\n");

        return 1;
    }
    uint16_t server_port = stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd == -1)
    {
        perror("socket");
        return 2;
    }
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    socklen_t len = sizeof(server);
    server.sin_family = AF_INET; 
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(argv[1]);
    //inet_pton(AF_INET, argv[1], &server.sin_addr);
    while (1)
    {
        string message;
        cout << "Please Enter# ";
        getline(cin, message);
        ssize_t n = sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));
        if (n == -1)
        {
            perror("sendto");
            close(sockfd);
            return 3;
        }

        char buffer[1024] = {0};
        // struct sockaddr_in peer;
        // socklen_t len = sizeof(peer);
        ssize_t m = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&server, &len);
        if (m == -1)
        {
            perror("recvfrom");
            close(sockfd);
            return 4;
        }
        buffer[m] = '\0'; 
        printf("%s\n",buffer);
    }

    close(sockfd);
    return 0;
}